package com.eclink.iot.tcp.virtualdevice.message;

import com.eclink.iot.tcp.virtualdevice.util.TimeUtil;
import lombok.Getter;

import java.util.ArrayList;
import java.util.List;

public class PingMessage extends Message {

    // Ping的类型是2
    @Getter
    private final byte code = 2;

    private final String uuid;

    private final String version;

    private long runtime;

    public PingMessage(String uuid) {
        this.uuid = uuid;
        this.version = this.generateVersion();
    }

    public void refreshRuntime() {
        this.runtime = System.currentTimeMillis();
    }

    private byte[] hexStringToBytes(String hexString) {

        if (hexString == null || hexString.isEmpty()) {
            return new byte[0];
        }

        byte[] bytes = new byte[hexString.length() / 2];
        for (int i = 0; i < hexString.length(); i += 2) {
            // 提取当前字符对应的两个16位数字字符
            String digitPair = hexString.substring(i, i + 2);
            // 将16位数字字符串转换为整数，再转换为字节
            bytes[i / 2] = (byte) Integer.parseInt(digitPair, 16);
        }
        return bytes;
    }

    private String generateVersion() {
        StringBuilder res = new StringBuilder();

        for(int i = 0; i < 24; i++){
            res.append(String.format("%02X", i));
        }
        return res.toString();
    }

    public List<Byte> getDataBytes() {
        // 状态
        byte status = 0;
        List<Byte> list = new ArrayList<Byte>();
        list.add(status);

        byte[] uuidBytes = hexStringToBytes(uuid);
        for(byte b : uuidBytes) {
            list.add(b);
        }

        byte[] versionBytes = hexStringToBytes(version);
        for(byte b : versionBytes) {
            list.add(b);
        }

        byte[] timeBytes = TimeUtil.transTimestampToBytes(runtime);
        for(byte b : timeBytes) {
            list.add(b);
        }

        return list;
    }

}
